﻿(function () {
	var container = null;
	var command_panel = null;
    var grid  = null;
	function init(){
		container = $("main");
		if (container){
            command_panel = container.getElement(".command-panel");
            grid = container.getElement(".grid table");

            if (QS.data.id){
                var row = $("row-"+ QS.data.id);
                if (row){
                    var selected = row.getElement("input[@radio]");
                    setCommandPanel(selected);
                }else{
                resetCommandPanel();
                }
            }else{
                resetCommandPanel(grid.getElement("tbody input[@radio]:checked"));
            }
            initEvents();
        }
	}	
    function initEvents(){
        grid.getElements("tbody td .uncheck").addEvent("click",function(e){
            var selected = grid.getElement("tbody input[@radio]:checked");
            resetCommandPanel(selected);
        });
        grid.getElements("tbody input[@radio]").addEvent("click",function(e){
            grid.getElements("tr.selected").removeClass("selected");
            setCommandPanel(this);
        });
    }
    function resetCommandPanel(selected){
        if (selected){
            selected.checked = false;
            selected.getParent("tr").removeClass("selected");
        }
        if (command_panel){
            command_panel.getElement(".edit-link").hide();
            command_panel.getElement(".delete-link").hide();
        }
    }
    function setCommandPanel(selected){
       if (selected ){
            selected.checked = true;
            selected.getParent("tr").addClass("selected");
            if (command_panel){
               var editBtn = command_panel.getElement(".edit-link");
               var deleteBtn = command_panel.getElement(".delete-link");

               QS.data.id  = selected.get("value");

               QS.data.cmd = "edit";
               QS.data.form  = QSParser("form", editBtn.get("href"));
               editBtn.set("href", location.pathname + "?" + QS.data.toQueryString()).show();

               QS.data.cmd = "delete";
               QS.data.form  = QSParser("form", deleteBtn.get("href"));
               deleteBtn.set("href", location.pathname + "?" + QS.data.toQueryString()).show();
            }
        }
    }
	$domready(init);
})();
